package com.wt.admin.service.ai.impl.agents;

import cn.hutool.core.util.ObjectUtil;
import com.aizuda.easy.security.exp.impl.BasicException;
import com.wt.admin.domain.dto.ai.AgentsInfoDTO;
import com.wt.admin.domain.entity.ai.MCPEntity;
import com.wt.admin.service.ai.impl.mcp.MCPStart;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.ChatOptions;

import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;


import java.util.*;

public abstract class AbstractAgentsBuilderService implements AgentsBuilderService{

    @Resource
    MCPStart mcpStart;
    @Resource
    ChatMemory chatMemory;

    ToolCallbackProvider getToolCallbackProvider(MCPEntity mcpEntities) {
        return switch (mcpEntities.getTag()) {
            case 0 -> mcpStart.builderMcpClientSTDIO(mcpEntities);
            case 1 -> mcpStart.builderMcpClientSSE(mcpEntities);
            case 2 -> mcpStart.builderMcpClientFlux(mcpEntities);
            default -> throw new RuntimeException("不支持的mcp类型");
        };
    }

    AgentsManager.ChatClientMapper build(ChatModel chatModel, AgentsInfoDTO agents, List<MCPEntity> mcpEntities, ChatOptions options){
        ChatClient.Builder builder = ChatClient.builder(chatModel)
                .defaultSystem("""
                        你是%s,你的名字是%s,%s
                        """.formatted(
                        Optional.ofNullable(agents.getName()).orElse(""),
                        Optional.ofNullable(agents.getName()).orElse(""),
                        Optional.ofNullable(agents.getBackground()).orElse(""))
                );
        ToolCallbackProvider[] allTools = mcpEntities.stream()
                .map(this::getToolCallbackProvider)
                .toArray(ToolCallbackProvider[]::new);
        if (allTools.length > 0) {
            builder.defaultToolCallbacks(allTools);
        }


        // 不建议使用工具，1. 很多大模型不支持 2. 不方便与外部建立连接
//        ToolCallback[] dateTimeTools = ToolCallbacks.from(new DateTimeTools(),new WeatherTools());
        return new AgentsManager.ChatClientMapper(builder.build(),options);
    }

}
